package com.cash.app.ui.main

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import coil3.load
import coil3.request.placeholder
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.APP_UPDATE_FORCE
import com.cash.app.constant.AppConstant.K_APP_SHOW_UPDATE
import com.cash.app.custom.AppActionBar
import com.cash.app.custom.CommonDialog
import com.cash.app.custom.ContactInfoView
import com.cash.app.databinding.AcMainBinding
import com.cash.app.databinding.DialogAppTipBinding
import com.cash.app.databinding.DialogVipProductBinding
import com.cash.app.databinding.ViewRatingBinding
import com.cash.app.manager.GlobalConfigManager
import com.cash.app.manager.GlobalTaskManager
import com.cash.app.manager.LoginManager
import com.cash.app.manager.model.VipProductResponse
import com.cash.app.ui.loan.LoanConfirmActivity
import com.cash.app.ui.login.LoginActivity
import com.cash.app.ui.main.fg.account.AccountFragment
import com.cash.app.ui.main.fg.home.HomeFragment
import com.cash.app.ui.main.fg.repay.RepayFragment
import com.cash.app.ui.main.model.MainViewModel
import com.cash.app.ui.other.SettingActivity
import com.cash.app.utils.AppLocationUtils
import com.cash.app.utils.NumberUtils
import com.cash.app.utils.SpUtils
import com.cash.app.utils.StatusBarUtil
import com.cash.app.utils.TLog
import com.cash.app.utils.ThirdAppUtils

private const val TAG = "MainActivity"

class MainActivity : BaseActivity() {

    private lateinit var binding: AcMainBinding
    private val viewModel: MainViewModel by viewModels()

    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: LinearLayout

    private lateinit var mainBgIv: ImageView
    private lateinit var mainActionBar: AppActionBar

    // Tab model
    private val tabs = listOf(
        TabItem(R.string.main_tab_home, R.drawable.main_tab_home),
        TabItem(R.string.main_tab_repay, R.drawable.main_tab_repay),
        TabItem(R.string.main_tab_account, R.drawable.main_tab_account),
    )

    override fun setViewBind() {
        binding = AcMainBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.mainActionBar
    }

    override val isFitsSystemWindows: Boolean
        get() = false

    override val isFitNavigationBarInsets: Boolean
        get() = true

    override val statusBarTextDark: Boolean
        get() = false

    override val statusBarColor: Int
        get() = R.color.transparent

    override fun setAppActionBar(actionBar: AppActionBar) {
        mainActionBar = actionBar
//        if (BuildConfig.DEBUG) {
//            mainActionBar.setLeftTextClickListener {
//                LoginActivity.start(this)
//            }
//        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        TLog.d("${StatusBarUtil.getStatusBarHeight(this)}", TAG)
        mainBgIv = binding.mainBgIv

        tabLayout = binding.mainTabLl
        viewPager = binding.mainContentVp

        setupViewPager()
        setupTabs()

        setContactUs()

        checkLocationPermission()

        initObserver()

        //checkAppDialog()

        //showRatingDialog()

        GlobalTaskManager.getMetaData()
    }

    override fun onResume() {
        super.onResume()
        viewModel.getAccountInfo()
    }

    private fun showRatingDialog() {
        val ratingView = ViewRatingBinding.inflate(LayoutInflater.from(this))
        var currentRating = ratingView.ratingBar.rating.toInt()
        ratingView.ratingBar.setOnRatingBarChangeListener { _, rating, _ ->
            currentRating = rating.toInt()
        }

        val ratingDialog = CommonDialog.Builder(this).apply {
            showTitle(true)
            setTitle(getString(R.string.loan_result_rating_title))
            setContentView(ratingView.root)
            setCancelable(true)
            setCancelableOnTouchOutside(false)
            addButton(
                text = getString(R.string.dislike), onClick = { dialog ->
                    dialog.dismiss()
                })
            addButton(
                text = getString(R.string.like), onClick = { dialog ->
                    //dialog.dismiss()
                    Toast.makeText(
                        this@MainActivity,
                        ratingView.ratingBar2.getRating().toString(),
                        Toast.LENGTH_SHORT
                    ).show()
                }, textColor = R.color.red_1
            )
        }.build()

        ratingDialog.show()
    }

    fun checkAppDialog() {
        if (GlobalConfigManager.isNeedUpdate()) {
            showUpdateDialog()
            return
        }
        if (GlobalConfigManager.isWindowOpen()) {
            showAppTipDialog()
            return
        }
        viewModel.getVipProduct()
    }

    private var showUpdateDialog = false
    private var showTipDialog = false
    private var showVipDialog = false

    private fun showUpdateDialog() {
        if (showUpdateDialog) {
            return
        }
        val dialogBinding = DialogAppTipBinding.inflate(layoutInflater)
        val version = GlobalConfigManager.getLatestVersion()
        with(dialogBinding) {
            tipContent.text = getString(R.string.check_update_tip, version)
        }
        val isForce = GlobalConfigManager.getUpdateType() == APP_UPDATE_FORCE
        CommonDialog.Builder(this).apply {
            showTitle(true)
            setTitle(getString(R.string.check_update_title))
            setContentView(dialogBinding.root)
            showButtons(true)
            if (!isForce) {
                addButton(getString(R.string.check_update_later), { dialog ->
                    SpUtils.put(K_APP_SHOW_UPDATE, false)
                    dialog.dismiss()
                }, R.color.black_1)
            }
            addButton(getString(R.string.check_update_now), { dialog ->
                ThirdAppUtils.gotoGP(this@MainActivity)
                dialog.dismiss()
            }, R.color.yellow_4)
            setCancelable(!isForce)
            setCancelableOnTouchOutside(!isForce)
            setOnDismissListener {
                showUpdateDialog = false
            }
        }.build().show()
        showUpdateDialog = true
    }

    private fun showAppTipDialog() {
        if (showTipDialog) {
            return
        }
        val dialogBinding = DialogAppTipBinding.inflate(layoutInflater)
        val windowContent = GlobalConfigManager.getWindowRemark()
        with(dialogBinding) {
            tipContent.text = windowContent
        }
        CommonDialog.Builder(this).apply {
            showTitle(true)
            setTitle(getString(R.string.tips))
            setContentView(dialogBinding.root)
            showButtons(true)
            addButton(getString(R.string.cancel), { dialog ->
                dialog.dismiss()
            }, R.color.black_1)
            setCancelable(true)
            setCancelableOnTouchOutside(true)
            setOnDismissListener {
                showTipDialog = false
            }
        }.build().show()
        showTipDialog = true
    }

    private fun initObserver() {
        viewModel.vipProduct.observe(this) { rsp ->
            if (rsp.show_special) {
//                // mock data
//                val gson = Gson()
//                val rsp = gson.fromJson(
//                    "{\n" + "  \"show_special\": true,\n" + "  \"pop_title\": \"VIP Products\",\n" + "  \"pop_desc\": \"Better than good,Better than good,Better than good,Better than good!\",\n" + "  \"pop_btn_title\": \"Apply Now\",\n" + "  \"p_id\": 1,\n" + "  \"p_name\": \"product1\",\n" + "  \"p_icon\": \"https://download.menggaliuang.io/picture/20231201/c123b7e0ba24041d643099dde98073a0.png\",\n" + "  \"p_money\": 300000,\n" + "  \"p_peroid\": 6,\n" + "  \"p_receive_amount\": 270000,\n" + "  \"p_common_receive_amount\": 210000\n" + "}",
//                    VipProductResponse::class.java
//                )
                showVipDialog(rsp)
            }
        }
    }

    private fun showVipDialog(vipProduct: VipProductResponse) {
        if (showVipDialog) {
            return
        }
        val dialogBinding = DialogVipProductBinding.inflate(layoutInflater)
        with(dialogBinding) {
            if (vipProduct.p_icon.isNotEmpty()) {
                vipIcon.load(vipProduct.p_icon) {
                    placeholder(R.mipmap.app_icon)
                }
            }
            vipProductName.text = vipProduct.p_name
            vipTip.text = vipProduct.pop_desc
            productMoney.text = NumberUtils.toRupeeWithComma(vipProduct.p_money)
            productReceiveMoney.text = NumberUtils.toRupeeWithComma(vipProduct.p_receive_amount)
            productCommonReceiveMoney.text =
                NumberUtils.toRupeeWithComma(vipProduct.p_common_receive_amount)
            productCommonReceiveMoney.paintFlags =
                productCommonReceiveMoney.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        }

        CommonDialog.Builder(this).apply {
            showTitle(true)
            setTitle(vipProduct.pop_title)
            setContentView(dialogBinding.root)
            showButtons(true)
            addButton(vipProduct.pop_btn_title, { dialog ->
                LoanConfirmActivity.start(
                    this@MainActivity,
                    vipProduct.p_id,
                    vipProduct.p_money,
                    vipProduct.p_peroid,
                    vipProduct.p_name,
                    vipProduct.p_icon,
                    true
                )
                dialog.dismiss()
            }, R.color.yellow_4)
            setCancelable(true)
            setCancelableOnTouchOutside(true)
            setOnDismissListener {
                showVipDialog = false
            }
        }.build().show()
        showVipDialog = true
    }

    private fun setContactUs() {
        mainActionBar.showRightIcon(GlobalConfigManager.showContactUs())
        mainActionBar.setRightIconClickListener {
            showContactDialog()
        }
    }

    private fun showContactDialog() {
        // Create contact info view
        val contactInfoView = ContactInfoView(this).apply {
            setContactInfo(
                email = GlobalConfigManager.getEmailAddress(),
                whatsApp = GlobalConfigManager.getWhatsApp1(),
                whatsApp2 = GlobalConfigManager.getWhatsApp2()
            )
        }

        // Show dialog with contact info
        CommonDialog.Builder(this).showTitle(true).setTitle(getString(R.string.app_contact_us))
            .setContentView(contactInfoView).showButtons(true)
            .addButton(getString(R.string.cancel), { dialog ->
                dialog.dismiss()
            }).setCancelable(true).setCancelableOnTouchOutside(true).build().show()
    }

    private val startSettingForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                setCurrentTab(0)
            }
        }

    private fun startSettingPage() {
        val intent = Intent(this, SettingActivity::class.java)
        startSettingForResult.launch(intent)
    }

    private fun setupViewPager() {
        val fragments = listOf(
            HomeFragment(), RepayFragment(), AccountFragment { startSettingPage() })

        viewPager.adapter = MainFragmentAdapter(this, fragments)

//        if (BuildConfig.DEBUG) {
//            viewPager.isUserInputEnabled = true
//            viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
//                override fun onPageSelected(position: Int) {
//                    super.onPageSelected(position)
//                    setCurrentTab(position)
//                }
//            })
//        }
        viewPager.isUserInputEnabled = false
    }

    private fun setupTabs() {
        tabs.forEachIndexed { index, tabItem ->
            val tabView = layoutInflater.inflate(R.layout.ac_main_tab_item, tabLayout, false)
            val icon = tabView.findViewById<ImageView>(R.id.tab_icon)
            val title = tabView.findViewById<TextView>(R.id.tab_title)

            icon.setImageResource(tabItem.icon)
            title.setText(tabItem.title)

            tabView.setOnClickListener {
                setCurrentTab(index)
            }

            tabLayout.addView(tabView)
        }

        setCurrentTab(0)
    }

    private fun setCurrentTab(position: Int) {
        if (!LoginManager.isLogin() && position != 0) {
            LoginActivity.start(this)
            return
        }
        if (viewPager.currentItem != 0 && position == 0) {
            checkAppDialog()
        }
        viewPager.currentItem = position
        val title = tabs[position].title
        when (title) {
            R.string.main_tab_home -> {
                mainBgIv.setImageResource(R.mipmap.home_bg)
                mainActionBar.showTitle(false)
                mainActionBar.showLeftText(true)
                mainActionBar.showRightIcon(GlobalConfigManager.showContactUs())
            }

            R.string.main_tab_repay -> {
                mainBgIv.setImageResource(R.mipmap.repay_bg)
                mainActionBar.showTitle(true)
                mainActionBar.showLeftText(false)
                mainActionBar.showRightIcon(false)
            }

            R.string.main_tab_account -> {
                mainBgIv.setImageResource(R.mipmap.common_bg)
                mainActionBar.showTitle(false)
                mainActionBar.showLeftText(false)
                mainActionBar.showRightIcon(GlobalConfigManager.showContactUs())
            }
        }
        for (i in 0 until tabLayout.childCount) {
            val tabView = tabLayout.getChildAt(i)
            val icon = tabView.findViewById<ImageView>(R.id.tab_icon)
            val title = tabView.findViewById<TextView>(R.id.tab_title)
            icon.isSelected = (i == position)
            title.isSelected = (i == position)
        }
    }

    private val locationPermissionCode = 100

    private fun checkLocationPermission() {
        val permission = Manifest.permission.ACCESS_COARSE_LOCATION

        if (ContextCompat.checkSelfPermission(
                this, permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            ActivityCompat.requestPermissions(
                this, arrayOf(permission), locationPermissionCode
            )
        } else {
            AppLocationUtils.startLocate()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == locationPermissionCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                AppLocationUtils.startLocate()
            } else {
                Toast.makeText(
                    this, "PERMISSION NOT GRANTED", Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    data class TabItem(
        val title: Int, val icon: Int
    )

    private inner class MainFragmentAdapter(
        fragmentActivity: FragmentActivity, private val fragments: List<Fragment>
    ) : FragmentStateAdapter(fragmentActivity) {

        override fun getItemCount(): Int = fragments.size

        override fun createFragment(position: Int): Fragment = fragments[position]
    }
}